from django.db import models
from django.contrib.auth.models import User
from google.appengine.ext import db



OPEN = 'OPEN'
SOLVED = 'SOLVED'
WILL_NOT_SOLVE = 'WILL_NOT_SOLVE'



class Problem(db.Model):
    """An undesired effect in a person or team's reality.
    A problem can be a root cause, i.e., not derived from
    any other problem, or can be caused by other
    problems."""
    
    STATUS_CHOICES = (
        OPEN,
        SOLVED,
        WILL_NOT_SOLVE,        
    )
    
    IMPORTANCE_CHOICES = (
        1,
        2,
        3,
        4,
        5,
    )

    name = db.StringProperty(required=True)
    person = db.ReferenceProperty(User, required=True)
    description = db.StringProperty()
    status = db.StringProperty(choices=STATUS_CHOICES)
    importance = db.IntegerProperty(choices=IMPORTANCE_CHOICES)
    is_initial_problem = db.BooleanProperty(default=False)
    tags = db.ListProperty(db.Category)
    issued = db.DateTimeProperty(auto_now=True)
    
    def __unicode__(self):
        return unicode(self.name)
    
    def populate_from_map(self, map, user):
        self.name = map["name"]
        self.person = user
        self.description = map["description"]
        self.status = OPEN
        self.importance = int(map["importance"])
        self.is_initial_problem = False
        
    def set_tags(self, tags_string):
        if tags_string != "":
            tags = []
            for t in tags_string.split(","):
                tag = db.Category(t)
                tags.append(tag)
            self.tags = tags


class CausalRelation(db.Model):
    person = db.ReferenceProperty(User, required=True)
    cause = db.ReferenceProperty(Problem, collection_name="cause", required=True)
    effect = db.ReferenceProperty(Problem, collection_name="effect", required=True)
    issued = db.DateTimeProperty(auto_now=True)
    
    def __unicode__(self):
        return "causal relation between %s and %s" % (self.cause.name, self.effect.name)
    